import * as api from '@/api/modules/interactive'
import { AliwangwangOutlined } from '@ant-design/icons-vue'
import { Button, notification } from 'ant-design-vue'
import { h } from 'vue'
import { TYPE, useToast } from 'vue-toastification'

import { useLoginAccountStoreWithOut } from '@/store/modules/login'
import router from '@/router'
import { createPermissionRouterGuard } from '@/router/guard/permissionGuard'

import * as permissionAuthApi from '@/api/modules/permission-temporary-authorization'
import * as userAuthApi from '@/views/demo/multi-factor-authorization/api-multi-factor-authorization';
import authModule from '@/views/temporary-authorization/components/toast-auth.vue'

const loginAccountStore = useLoginAccountStoreWithOut()
const toast = useToast()

export default async function setupSignalR() {  
  let token = loginAccountStore.getToken
  if (token === null || token === '') {
    return;
  }
  
  await api.default.buildConnection()
  api.default.attachToHub('ReceiveNotification', (record: any) => {
    toast(record.data, { timeout: 3000, type: TYPE.DEFAULT })
  });

  api.default.attachToHub('UserSensitiveDataTemporaryAuthorization', (record: any) => {
    let id = `user-temp-auth-${record?.data.commiter}`;

    if (record.data.key == undefined || record.data.key == null) {
      toast.update(id, { content: record.data.description, options: { timeout: 2000, type: TYPE.SUCCESS } })
    } else { 
      toast({
        component: authModule,
        listeners: {
          reject: () => {            
            userAuthApi.reject(record?.data.key);
          },
          grant: () => {            
            userAuthApi.grant(record?.data.key);
          }
        },
        props: {
          context: record
        },
      }, {
        id: id
      })
    }        
  })

  api.default.attachToHub('PermissionTemporaryAuthorization', (record: any) => {
    let id = `permission-temp-auth-${record?.data.commiter}`;

    if (record?.data.status == -1) {      
      createPermissionRouterGuard(router, true);

      toast(record.data.description, { timeout: 2000, type: TYPE.DEFAULT })

      return;
    }
    
    if (record.data.key == undefined || record.data.key == null) {
      toast.update(id, { content: record.data.description, options: { timeout: 2000, type: TYPE.SUCCESS } })
    } else {
      toast({
        component: authModule,
        listeners: {
          reject: () => {
            permissionAuthApi.reject(record?.data.key);
          },
          grant: () => {
            permissionAuthApi.grant(record?.data.key);
          }
        },
        props: {
          context: record
        },
      }, {
        id: id
      })
    }
  })
  
  let res = await api.default.startConnect();
  if (res === true) {
    let roleCode = await api.default.getRoleCode();

    roleCode.forEach(async (e: string) => {
      await api.default.addToGroupAsync(e);
    });
  }    
}